sap.ui.define([
	"../BaseController",
	"../ItemDetailDialog",
	"sap/ui/model/json/JSONModel",
	"../../model/formatter",
	"sap/m/library"
], function(BaseController, ItemDetailDialog, JSONModel, formatter) {
	"use strict";

	// shortcut for sap.m.URLHelper
	//	var URLHelper = mobileLibrary.URLHelper;

	return BaseController.extend("com.wp.SWIFTSAP.controller.outbox.OutboxDetail", {

		formatter: formatter,

		/* =========================================================== */
		/* lifecycle methods                                           */
		/* =========================================================== */

		onInit: function() {
			// Model used to manipulate control states. The chosen values make sure,
			// detail page is busy indication immediately so there is no break in
			// between the busy indication for loading the view's meta data
			var oViewModel = new JSONModel({
				busy: false,
				delay: 0,
				lineItemTableDelay: 0,
				lineItemListTitle: this.getResourceBundle().getText("detailLineItemTableHeading"),
				historyItemListTitle: this.getResourceBundle().getText("historyLineItemTableHeading"),
				headjson: "",
				itemhjson: "",
				itemrjson: "",
				attachjson: "",
				historyjson: "",
				itemDetailJSON: "",
				headerNoteLable: "",
				headerNoteText: ""
			});

			//Attach related start----->
			// Sets the text to the label
			this.byId("uploadCollection").addEventDelegate({
				onBeforeRendering: function() {
					this.byId("attachmentTitle").setText(this.getAttachmentTitleText());
				}.bind(this)
			});
			this._PDFViewer = null;
			this.vRequestid = null;
			//Attach related end-----<

			this.getRouter().getRoute("outboxDetail").attachPatternMatched(this._onRequestMatched, this);
			this.setModel(oViewModel, "detailView");
			this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bind(this));
		},

		productItemFactory: function(sId, oContext) {
			var oUIControl = [];
			var sObj = oContext.getObject();
			for (var i in sObj) { //遍历所有属性 
				oUIControl.push(new sap.m.Text({
					text: sObj[i]
				}));
			}

			var oView = this.getView();
			var oDialog = new ItemDetailDialog(oView);

			var onPressToItemDetail = function(oEvent) {
				//var test = oEvent.oSource.getBindingContext();
				//实际是获取View
				//获取屏幕点击的ObjectListItem 元素
				var oItem = oEvent.getSource();

				// var msg = oItem.getBindingContext("invoice").getPath();
				// alert(msg); /Invoices/2  下面substr(1)是为了去掉开始的'/'
				var itemHData = oItem.getModel("detailView").getProperty("/itemhjson");
				var itemRData = oItem.getBindingContext("detailView").getObject();
				//合并行项目详细信息
				var itemDetailData = itemHData.map(function(item) {
					var vField = item.FIELD;
					//拼接的字段替换
					if (vField.indexOf("&")) {
						vField = vField.replace(/\&/g, "_");
					}
					for (var attr in itemRData) {
						if (attr === vField) {
							item.VALUE = itemRData[attr];
							break;
						}
					}
					return item;
				});
				oItem.getModel("detailView").setProperty("/itemDetailJSON", itemDetailData);
				oDialog.open(oView);
			};

			return new sap.m.ColumnListItem({
				cells: oUIControl,
				type: "Active",
				press: onPressToItemDetail
			});
		},

		/* =========================================================== */
		/* event handlers                                              */
		/* =========================================================== */
		/**
		 * Updates the item count within the line item table's header
		 * @param {object} oEvent an event containing the total number of items in the list
		 * @private
		 */
		onListUpdateFinished: function(oEvent) {
			var sTitle,
				iTotalItems = oEvent.getParameter("total"),
				oViewModel = this.getModel("detailView");

			// only update the counter if the length is final
			if (this.byId("lineItemsList").getBinding("items").isLengthFinal()) {
				if (iTotalItems) {
					sTitle = this.getResourceBundle().getText("detailLineItemTableHeadingCount", [iTotalItems]);
				} else {
					//Display 'Line Items' instead of 'Line items (0)'
					sTitle = this.getResourceBundle().getText("detailLineItemTableHeading");
				}
				oViewModel.setProperty("/lineItemListTitle", sTitle);
			}
		},

		/* =========================================================== */
		/* begin: internal methods                                     */
		/* =========================================================== */

		/**
		 * Binds the view to the object path and expands the aggregated line items.
		 * @function
		 * @param {sap.ui.base.Event} oEvent pattern match event in route 'object'
		 * @private
		 */
		_onRequestMatched: function(oEvent) {
			var sRequestid = oEvent.getParameter("arguments").Requestid;
			this.vRequestid = sRequestid;

			var sPath = "/RequestSet('" + sRequestid + "')";
			var oRequest = this.getModel().getProperty(sPath);
			if (!oRequest) { //浏览器直接刷新过来侧直接返回
				//return;
			}

			this.getModel("appView").setProperty("/layout", "TwoColumnsMidExpanded");
			var oViewModel = this.getModel("detailView");

			var oItemTable = this.getView().byId("lineItemsList");
			var oUploadCollection = this.getView().byId("uploadCollection");

			oItemTable.setVisible(true);
			this.byId("downloadButton").setEnabled(false);
			oItemTable.setVisible(true);
			oUploadCollection.setVisible(true);

			var fRequestid = new sap.ui.model.Filter({
				path: "Requestid",
				operator: sap.ui.model.FilterOperator.EQ,
				value1: sRequestid
			});
			var oFilter = [];
			oFilter.push(fRequestid);

			this.getModel().metadataLoaded().then(function() {
				//读取request信息
				var sObjectPath = this.getModel().createKey("RequestSet", {
					Requestid: sRequestid
				});
				this._bindView("/" + sObjectPath); //RequestSet(Requestid="")
				var vLanguage = this.getOwnerComponent().getModel("user").getProperty("/Language");
				//读取request 行项目信息
				var sObjectPath01 = this.getModel().createKey("/ReqjsonSet", {
					Requestid: sRequestid
				});

				this.getModel().attachRequestSent(function() {
					sap.ui.core.BusyIndicator.show();
				});

				this.getModel().attachRequestCompleted(function() {
					sap.ui.core.BusyIndicator.hide();
				});

				this.getModel().read(sObjectPath01, {
					success: function(oData) {
						var oHeadjson = oData.Headjson,
							oItemhjson = oData.Itemhjson,
							oItemrjson = oData.Itemrjson,
							oAttachjson = oData.Attachjson;

						if (oHeadjson !== "") {
							oHeadjson = JSON.parse(oHeadjson);
							oHeadjson.shift();
							//多语言支持 
							for (var i in oHeadjson) {
								if (vLanguage.indexOf("zh") !== -1) {
									oHeadjson[i].NAME3 = oHeadjson[i].NAME1;
								} else if (vLanguage.indexOf("en") !== -1) {
									oHeadjson[i].NAME3 = oHeadjson[i].NAME2;
								}
								if (oHeadjson[i].FIELD === "ZTETXH") {
									//replace all "|" with "\t\n"
									if (oHeadjson[i].VALUE) {
										oHeadjson[i].VALUE = oHeadjson[i].VALUE.replace(/\|/g, "\t\n");
									}

									this.getView().getModel("detailView").setProperty("/headerNoteLable", oHeadjson[i].NAME3);
									this.getView().getModel("detailView").setProperty("/headerNoteText", oHeadjson[i].VALUE);
									oHeadjson[i]["VISIBLE"] = false;
								} else {
									oHeadjson[i]["VISIBLE"] = true;
								}
								if (oHeadjson[i].FIELD === "LBLNI" || oHeadjson[i].FIELD === "EBELN" || oHeadjson[i].FIELD === "LIFNR") {
									oHeadjson[i]["ATTACTIVE"] = true;
								} else {
									oHeadjson[i]["ATTACTIVE"] = false;
								}
							}
						}
						if (oItemrjson !== "") {
							oItemrjson = JSON.parse(oItemrjson);
						} else {
							oItemTable.setVisible(false);
						}
						if (oItemhjson !== "") {
							oItemhjson = JSON.parse(oItemhjson);
							//多语言支持 
							for (var j in oItemhjson) {
								if (vLanguage.indexOf("zh") !== -1) {
									oItemhjson[j].NAME3 = oItemhjson[j].NAME1;
								} else if (vLanguage.indexOf("en") !== -1) {
									oItemhjson[j].NAME3 = oItemhjson[j].NAME2;
								}
								oItemhjson[j].VISIBLE = true;
								if (oItemrjson.length > 0) {
									var oItemRow0 = oItemrjson[0];
									if (oItemRow0[oItemhjson[j]["FIELD"]] === "") {
										oItemhjson[j].VISIBLE = false;
									}
								}
								if (oItemhjson[j].FIELD === "EXTROW" || oItemhjson[j].FIELD === "MEINS") {
									oItemhjson[j].WITH = "3rem";
								} else if (oItemhjson[j].FIELD === "MENGE" || oItemhjson[j].FIELD === "TBTWR" || oItemhjson[j].FIELD === "BRTWR") {
									oItemhjson[j].WITH = "5rem";
								} else if (oItemhjson[j].FIELD === "KTEXT1") {
									oItemhjson[j].WITH = "20%";
								} else if (oItemhjson[j].FIELD === "AUFNR" || oItemhjson[j].FIELD === "KOSTL" || oItemhjson[j].FIELD === "SAKTO") {
									oItemhjson[j].WITH = "6rem";
								} else if (oItemhjson[j].FIELD === "TXT20" || oItemhjson[j].FIELD === "KTEXT2" || oItemhjson[j].FIELD === "KTEXT") {
									oItemhjson[j].WITH = "12%";
								}
							}
						}

						if (oAttachjson !== "") {
							oAttachjson = JSON.parse(oAttachjson);
						} else { //隐藏附件控件
							oUploadCollection.setVisible(false);
						}

						oViewModel.setProperty("/headjson", oHeadjson);
						oViewModel.setProperty("/itemhjson", oItemhjson);
						oViewModel.setProperty("/itemrjson", oItemrjson);
						oViewModel.setProperty("/attachjson", oAttachjson);
					}.bind(this),
					error: function(oData) {
						oViewModel.setProperty("/headjson", "");
						oViewModel.setProperty("/itemhjson", "");
						oViewModel.setProperty("/itemrjson", "");
						oViewModel.setProperty("/attachjson", "");
						this.showErrorMessage(oData.message);
					}.bind(this)
				});

				//读取request 历史信息
				this.getModel().read("/HistorySet", {
					filters: [oFilter],
					success: function(oData) {
						//多语言支持 
						for (var i in oData.results) {
							if (vLanguage.indexOf("zh") !== -1) {
								oData.results[i].Applevel_desc3 = oData.results[i].Applevel_desc1;
							} else if (vLanguage.indexOf("en") !== -1) {
								oData.results[i].Applevel_desc3 = oData.results[i].Applevel_desc2;
							}
						}
						oViewModel.setProperty("/historyjson", oData.results);
					},
					error: function(oData) {
						oViewModel.setProperty("/historyjson", "");
						this.showErrorMessage(oData.message);
					}.bind(this)
				});

			}.bind(this));
		},

		/**
		 * Binds the view to the object path. Makes sure that detail view displays
		 * a busy indicator while data for the corresponding element binding is loaded.
		 * @function
		 * @param {string} sObjectPath path to the object to be bound to the view.
		 * @private
		 */
		_bindView: function(sObjectPath) {
			// Set busy indicator during view binding
			var oViewModel = this.getModel("detailView");

			// If the view was not bound yet its not busy, only if the binding requests data it is set to busy again
			oViewModel.setProperty("/busy", false);

			this.getView().bindElement({
				path: sObjectPath,
				events: {
					change: this._onBindingChange.bind(this),
					dataRequested: function() {
						oViewModel.setProperty("/busy", true);
					},
					dataReceived: function() {
						oViewModel.setProperty("/busy", false);
					}
				}
			});
		},

		_onBindingChange: function() {
			var oView = this.getView(),
				oElementBinding = oView.getElementBinding();

			// No data for the binding
			if (!oElementBinding.getBoundContext()) {
				this.getRouter().getTargets().display("detailObjectNotFound");
				// if object could not be found, the selection in the inbox list
				// does not make sense anymore.
				this.getOwnerComponent().oListSelector.clearMasterListSelection();
				return;
			}

			var sPath = oElementBinding.getPath();
			/*				oResourceBundle = this.getResourceBundle(),
							oObject = oView.getModel().getObject(sPath),
							sObjectId = oObject.ObjectID,
							sObjectName = oObject.Name,
							oViewModel = this.getModel("detailView");*/

			this.getOwnerComponent().oListSelector.selectAListItem(sPath);

			/*			oViewModel.setProperty("/shareSendEmailSubject",
							oResourceBundle.getText("shareSendEmailObjectSubject", [sObjectId]));
						oViewModel.setProperty("/shareSendEmailMessage",
							oResourceBundle.getText("shareSendEmailObjectMessage", [sObjectName, sObjectId, location.href]));*/
		},

		_onMetadataLoaded: function() {
			// Store original busy indicator delay for the detail view
			var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(),
				oViewModel = this.getModel("detailView"),
				oLineItemTable = this.byId("lineItemsList"),
				iOriginalLineItemTableBusyDelay = oLineItemTable.getBusyIndicatorDelay();

			// Make sure busy indicator is displayed immediately when
			// detail view is displayed for the first time
			oViewModel.setProperty("/delay", 0);
			oViewModel.setProperty("/lineItemTableDelay", 0);

			oLineItemTable.attachEventOnce("updateFinished", function() {
				// Restore original busy indicator delay for line item table
				oViewModel.setProperty("/lineItemTableDelay", iOriginalLineItemTableBusyDelay);
			});

			// Binding the view will set it to not busy - so the view is always busy if it is not bound
			oViewModel.setProperty("/busy", true);
			// Restore original busy indicator delay for the detail view
			oViewModel.setProperty("/delay", iOriginalViewBusyDelay);
		},

		/**
		 * Set the full screen mode to false and navigate to inbox page
		 */
		onCloseDetailPress: function() {
			this.getModel("appView").setProperty("/actionButtonsInfo/midColumn/fullScreen", false);
			this.getModel("appView").setProperty("/layout", "OneColumn");
			// No item should be selected on inbox after detail page is closed
			this.getOwnerComponent().oListSelector.clearMasterListSelection();
			this.getRouter().navTo("outbox", {
				Userid: this.getOwnerComponent().getModel("user").getProperty("/Userid")
			});
		},

		/**
		 * Toggle between full and non full screen mode.
		 */
		toggleFullScreen: function() {
			var bFullScreen = this.getModel("appView").getProperty("/actionButtonsInfo/midColumn/fullScreen");
			this.getModel("appView").setProperty("/actionButtonsInfo/midColumn/fullScreen", !bFullScreen);
			if (!bFullScreen) {
				// store current layout and go full screen
				this.getModel("appView").setProperty("/previousLayout", this.getModel("appView").getProperty("/layout"));
				this.getModel("appView").setProperty("/layout", "MidColumnFullScreen");
			} else {
				// reset to previous layout
				this.getModel("appView").setProperty("/layout", this.getModel("appView").getProperty("/previousLayout"));
			}
		},

		/**
		 * Attachment related
		 */
		getAttachmentTitleText: function() {
			var aItems = this.byId("uploadCollection").getItems();
			return this.getResourceBundle().getText("attachmentTitleText") + "(" + aItems.length + ")";
		},
		onDownloadItem: function() {
			var oUploadCollection = this.byId("uploadCollection");
			var aSelectedItems = oUploadCollection.getSelectedItems();
			var oItem = null;
			var vSwiftSAPHost = this.getOwnerComponent().getModel("user").getProperty("/Swiftsaphost");
			if (aSelectedItems) {
				for (var i = 0; i < aSelectedItems.length; i++) {
					oItem = aSelectedItems[i];
					//调用Odata服务
					var sObjectPath01 = this.getModel().createKey("/AttachSet", {
						ATTACHID: oItem.getDocumentId()
					});
					//sObjectPath01 = this.getResourceBundle().getText("appAttachHost") + sObjectPath01 + "/$value";
					sObjectPath01 = vSwiftSAPHost + "/sap/opu/odata/sap/YBC_SWIFTSAP_SRV" + sObjectPath01 + "/$value";
					var w = window.open(sObjectPath01, '_blank');
					if (w == null) {
						this.showErrorMessage("Download file failed, please retry!");
					}

				}
			} else {
				this.showErrorMessage("Select an item to download");
			}
		},

		onSelectionChange: function() {
			var oUploadCollection = this.byId("uploadCollection");
			if (oUploadCollection.getSelectedItems().length > 0) {
				this.byId("downloadButton").setEnabled(true);
			} else {
				this.byId("downloadButton").setEnabled(false);
			}
		},
		onCrossApplicationNavigation: function(semanticObject, sAction, oParams) {
			var oCrossAppNavigator = sap.ushell.Container.getService("CrossApplicationNavigation"); // get a handle on the global XAppNav service
			var hash = (oCrossAppNavigator && oCrossAppNavigator.hrefForExternal({
				target: {
					semanticObject: semanticObject,
					action: sAction
				},
				params: oParams
			})) || ""; // generate the Hash to display a Mapping
			oCrossAppNavigator.toExternal({
				target: {
					shellHash: hash
				}
			}); // navigate to Mapping application
		},
		onPressNumber: function(oEvent) {
			var oBindingData = oEvent.getSource().getBindingContext("detailView").getObject();
			var sSupplier = "";
			if (oBindingData.VALUE) {
					if (oBindingData.VALUE.split("(")[1]) {
						sSupplier = oBindingData.VALUE.split("(")[1].split(")")[0];
					} else {
						sSupplier = oBindingData.VALUE;
					}

				}
			switch (oBindingData.FIELD) {
				case "LBLNI":
					this.onCrossApplicationNavigation("Z_MMPURUIML81N", "display", {
						"P_LBLNI": oBindingData.VALUE,
						"sap-ui-tech-hint": "GUI"
					});
					break;
				case "EBELN":
					this.onCrossApplicationNavigation("Z_MMPURPAMEPO", "display", {
						"P_EBELN": oBindingData.VALUE,
						"sap-ui-tech-hint": "GUI"
					});
					//this.onCrossApplicationNavigation("PurchaseOrder","displayFactSheet",{"PurchaseOrder":oBindingData.VALUE});
					break;
				case "LIFNR":
					//this.onCrossApplicationNavigation("Supplier","displayPurchasingDetails",{"I_LIFNR-LOW":sSupplier,"sap-ui-tech-hint":"GUI"});
					this.onCrossApplicationNavigation("Supplier", "displayFactSheet", {
						"Supplier": sSupplier
					});
					break;
				default:
					break;

			}

		}

	});

});